﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Net.Mail;
using System.Net;
using NLog;

namespace Bingosoft.Swimming.Core.Helper
{
    public static class EmailHelper
    {
        static SmtpConfig config;
        static SmtpClient smtpClient;
        static EmailHelper()
        {
            config = SmtpConfig.GetInstance();
            smtpClient = new SmtpClient();
            smtpClient.Host = config.SmtpService;
            smtpClient.Port = config.SmtpPort;
            smtpClient.Credentials = new NetworkCredential(config.SmtpUserName, config.SmtpPassword);
        }

        public static bool Send(string from, string to, string subject, string body)
        {
            MailMessage mailMessage = new MailMessage();
            mailMessage.Subject = subject;
            mailMessage.Body = body;
            mailMessage.To.Add(to);
            mailMessage.Sender = mailMessage.From = new MailAddress(from);
            try
            {
                smtpClient.Send(mailMessage);
                LogManager.GetCurrentClassLogger().Trace("发邮件{0}成功", to);
                return true;
            }
            catch (Exception ex)
            {
                LogManager.GetCurrentClassLogger().ErrorException("发邮件错误", ex);
                return false;
            }
        }
    }

    public class SmtpConfig : ConfigurationSection
    {
        public const string Smtp_Service = "SmtpService";
        public const string Smtp_Port = "SmtpPort";
        public const string Smtp_UserName = "SmtpUserName";
        public const string Smtp_Password = "SmtpPassword";

        public static SmtpConfig GetInstance()
        {
            SmtpConfig config = ConfigurationManager.GetSection("SmtpConfig") as SmtpConfig;
            return config;
        }

        [ConfigurationProperty(Smtp_Service, IsRequired = true)]
        public string SmtpService
        {
            get
            {
                return this[Smtp_Service] as string;
            }
        }

        [ConfigurationProperty(Smtp_Port, IsRequired = false, DefaultValue=25)]
        public int SmtpPort
        {
            get
            {
                return Convert.ToInt32(this[Smtp_Port]);
            }
        }

        [ConfigurationProperty(Smtp_UserName, IsRequired = true)]
        public string SmtpUserName
        {
            get
            {
                return this[Smtp_UserName] as string;
            }
        }

        [ConfigurationProperty(Smtp_Password, IsRequired = true)]
        public string SmtpPassword
        {
            get
            {
                return this[Smtp_Password] as string;
            }
        }
    }


}
